import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:basic/basic.dart';
import 'package:core/core.dart';

import '../app_config.dart';
import '../manager/user_manager.dart';

final Http http = Http(); // https://api.polyfilm.shopdt.cn

class Http extends BaseHttp {
  final String baseUrl = "https://api.polyfilm.shopdt.cn";

  @override
  void init() {
    options.baseUrl = baseUrl;
    options.responseType = ResponseType.plain;
    interceptors
      ..add(ApiHeaderInterceptor())
      ..add(ApiInterceptor());
  }

  void reSet() {
    options.baseUrl = baseUrl;
    interceptors
      ..clear()
      ..add(ApiHeaderInterceptor())
      ..add(ApiInterceptor());
  }
}

///header拦截器
class ApiHeaderInterceptor extends HeaderInterceptor {
  @override
  onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    options.connectTimeout = const Duration(seconds: 45);
    options.receiveTimeout = const Duration(seconds: 45);
    String? token = UserManager.getToken();
    if (token != null) {
      if (!options.headers.keys.contains("token")) {
        options.headers['token'] = token;
      }
    }
    options.headers.addAll({'merchantId': '0', 'sassAppId': '0'});
    super.onRequest(options, handler);
  }
}

///post
class PostApiHeaderInterceptor extends HeaderInterceptor {
  @override
  onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    options.connectTimeout = const Duration(seconds: 45);
    options.receiveTimeout = const Duration(seconds: 45);
    String? token = UserManager.getToken();
    if (token != null) {
      if (!options.headers.keys.contains("token")) {
        options.headers['token'] = token;
      }
    }

    options.headers.addAll({
      'appVersion': AppConfig.versionName,
      'merchantId': '0',
      'sassAppId': '0',
    });
    super.onRequest(options, handler);
  }
}

/// API拦截器
class ApiInterceptor extends InterceptorsWrapper {
  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    if (!AppConfig.isRelease) {
      Map<String, dynamic> params = {};
      if (options.data != null && options.data is Map<String, dynamic>) {
        params = options.data;
      } else {
        params = options.queryParameters;
      }

      //添加打印token
      // String? token = UserManager.getToken();
      // if (token != null)
      //   params.addAll(Map<String, String>.from({'token': token}));

      String url = UriUtils.fullUri(
        options.baseUrl,
        path: options.path,
        queryParameters: params,
      );
      log('---api-request-url---> $url'); //发布版本不打印
    }
    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (!AppConfig.isRelease) {
      log('---api-response---> ${response.data.toString().trim()}'); //发布版本不打印
    }

    Map<String, dynamic> result;
    if (response.data is Map) {
      result = response.data;
    } else {
      result = json.decode(response.data);
    }
    ResponseData respData = ResponseData.fromJson(result);
    if (respData.success) {
      response.data = respData.data;
      return handler.next(response);
    } else {
      throw ApiException.fromRespData(respData);
    }
  }

  // @override
  // void onError(DioError err, ErrorInterceptorHandler handler) {
  //   super.onError(err, handler);
  //   LogUtil.v('---api-onError---> ${err.toString()}');
  // }
}

class ResponseData extends BaseResponseData {
  bool get success => "1" == code;

  ResponseData.fromJson(Map<String, dynamic> json) {
    code = json['code'].toString() as int;
    message = json['message'] ?? "";
    data = json['content'];
  }
}
